import { createRouter, createWebHistory } from 'vue-router'
import {get} from "@/utils/request";
import store from "@/store";
import Setting from "@/utils/setting";

const  Layout=() => import('@/layout/index.vue')

const  constRoutes=[
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue')
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/index.vue'),
        name: 'Dashboard',
        meta: { title: '首页', icon: 'monitor', affix: true, noCache: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'home',
    component: () => import('../views/login.vue'),
    hidden: true
  },
  {
    path: '/user',
    component: Layout,
    hidden: true,
    redirect: 'noredirect',
    children: [
      {
        path: 'center',
        component: () => import('@/views/system/user/center'),
        name: '个人中心',
        meta: { title: '个人中心' }
      }
    ]
  }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constRoutes
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + Setting.title
  }
  // 已登录且要跳转的页面是登录页
  if (to.path === '/login'||to.path==='/bind'||to.path==='/mobile') {
    next()
  } else {
    if (!store.state.isLoadMenu) {
      store.dispatch('getUserInfo').then(res=>{
        loadMenus(next, to)
      })
    } else {
      next()
    }
  }
})

const modules = import.meta.glob("../views/**");

export const loadMenus = (next, to) => {
  get('/menus/build').then(res => {
    let menus=initMenu(res)
    menus.forEach(item=>{
      router.addRoute(item)
    })
    next({...to, replace: true})
    menus=constRoutes.concat(menus)
    store.dispatch('setMenus',menus)
  })
}

function  initMenu(menus){
   menus.forEach(item=>{
      if(item.component==="Layout"){
        item.component=Layout
      }else{
        item.component=modules[`../views/${item.component}.vue`];
      }
     if(item.children){
       initMenu(item.children)
     }
   })
  return menus
}

export default router
